﻿


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Controls.DataVisualization.Charting;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Microsoft.Maps.MapControl;
using System.Windows.Data;
using System.Text.RegularExpressions;
using System.Threading;
using System.Collections;
using System.Collections.ObjectModel;

namespace SL4_NAV_ProjectiCON.Views
{
    public partial class Dashboard : Page
    {
        int PageNumber = 0;
        int PageIndex = 7;
        private Random _random = new Random();
        List<MonthlyActivity> monthlyActivity = new List<MonthlyActivity>();

        public Dashboard()
        {
            InitializeComponent();
        }

        protected void MyMap_Loaded(object sender, RoutedEventArgs e)
        {
            int busyDisplay = 3;
            int delayDisplay = 500;
            BusyWindow.DisplayAfter = TimeSpan.FromMilliseconds(delayDisplay);
            BusyWindow.IsBusy = true;
            ThreadPool.QueueUserWorkItem((state) =>
            {
                Thread.Sleep(busyDisplay * 1000);
                Dispatcher.BeginInvoke(() => BusyWindow.IsBusy = false);
            });

            Clear();
            SL4_NAV_ProjectiCON.DataService.DataServiceClient objCust = new SL4_NAV_ProjectiCON.DataService.DataServiceClient();
            objCust.GetCustomersCompleted += new EventHandler<SL4_NAV_ProjectiCON.DataService.GetCustomersCompletedEventArgs>(GetCustomersCompleted);
            objCust.GetCustomersAsync();

        }

        void GetCustomersCompleted(object sender, SL4_NAV_ProjectiCON.DataService.GetCustomersCompletedEventArgs e)
        {
            foreach (SL4_NAV_ProjectiCON.DataService.Customer C in e.Result)
            {
                CustomerPushpin pin;
                Location d = new Location(Convert.ToDouble(C.Latitude), Convert.ToDouble(C.Longitude));
                if (C.CustomerId > 10050)
                    pin = new CustomerPushpin(Colors.Blue);
                else
                    pin = new CustomerPushpin(Colors.Red);

                pin.Location = d;
                pin.Name = C.CustomerId.ToString();
                pin.CustomerId = C.CustomerId.ToString();
                pin.CustomerName = C.CustomerName.ToString();
                ScaleTransform st = new ScaleTransform();
                st.ScaleX = 0.25;
                st.ScaleY = 0.25;
                st.CenterX = (pin as FrameworkElement).Height / 2;
                st.CenterY = (pin as FrameworkElement).Height / 2;

                pin.RenderTransform = st;
                pin.MouseEnter += new MouseEventHandler(point_MouseEnter);
                pin.MouseLeave += new MouseEventHandler(point_MouseLeave);
                PushPinLayer.AddChild(pin, d);
            }
        }

        public void Clear()
        {
            List<UIElement> elementsToRemove = new List<UIElement>();
            List<UIElement> pushpinToRemove = new List<UIElement>();
            foreach (UIElement element in MyMap.Children)
            {
                if (element.GetType() == typeof(MapLayer))
                {
                    MapLayer Lay = (MapLayer)element;
                    if (Lay.Name == "PushPinLayer")
                    {
                        foreach (UIElement p in Lay.Children)
                        {
                            if (p.GetType() == typeof(CustomerPushpin))
                            {
                                pushpinToRemove.Add(p);
                            }
                        }
                        foreach (UIElement pin in pushpinToRemove)
                        {
                            Lay.Children.Remove(pin);
                        }
                    }
                    elementsToRemove.Add(Lay);
                }
            }
           
        }

        void point_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            // Show a popup with data about that point
            CustomerPushpin pin = sender as CustomerPushpin;
            if (pin != null)
            {
                MapLayer.SetPosition(ContentPopup, pin.Location);
                MapLayer.SetPositionOffset(ContentPopup, new Point(0, -60));



                string contentString = pin.CustomerId.ToString() + "   " + pin.CustomerName.ToString();
                //Remove tags from the string
                Regex regex = new Regex("<(.|\n)*?>");
                contentString = regex.Replace(contentString, string.Empty);
                ContentPopupText.Text = contentString;
                ContentPopup.Visibility = Visibility.Visible;

               // ReLoad(pin.CustomerName.ToString());
                monthlyActivity = MonthlyActivity.GetAll();
                ShowSummaryView();


            }
        }

        public void ReLoad(String objCuststr)
        {
            int busyDisplay = 3;
            int delayDisplay = 500;
            BusyWindow.DisplayAfter = TimeSpan.FromMilliseconds(delayDisplay);
            BusyWindow.IsBusy = true;
            ThreadPool.QueueUserWorkItem((state) =>
            {
                Thread.Sleep(busyDisplay * 1000);
                Dispatcher.BeginInvoke(() => BusyWindow.IsBusy = false);
            });
            Clear();
            SL4_NAV_ProjectiCON.DataService.DataServiceClient objCust1 = new SL4_NAV_ProjectiCON.DataService.DataServiceClient();
            objCust1.GetCustomersBynameCompleted += new EventHandler<SL4_NAV_ProjectiCON.DataService.GetCustomersBynameCompletedEventArgs>(GetCustomersByNameCompleted);
            objCust1.GetCustomersBynameAsync(objCuststr);

        }

        void GetCustomersByNameCompleted(object sender, SL4_NAV_ProjectiCON.DataService.GetCustomersBynameCompletedEventArgs e)
        {
            //dataGrid1.ItemsSource = e.Result;

        }

        void point_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            //Hide the popup
            CustomerPushpin point = sender as CustomerPushpin;
            ContentPopup.Visibility = Visibility.Collapsed;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

     


        private void ShowSummaryView()
        {
            // Create the column series associated with the monthly sales information
            ColumnSeries columnSeries = new ColumnSeries();
            // x value
            columnSeries.IndependentValueBinding = new Binding("Activities");
            columnSeries.Title= "Activities";
            // y value
            columnSeries.DependentValueBinding = new Binding("TotalActivity");
            columnSeries.Title = "Sum of Activities";
            columnSeries.IsSelectionEnabled = true;
            columnSeries.SelectionChanged += new SelectionChangedEventHandler(columnSeries_SelectionChanged);
            columnSeries.ItemsSource = monthlyActivity;

            // Make sure only the summary series is visible
            myChart.Series.Clear();
            myChart.Series.Add(columnSeries);
        }

        void columnSeries_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ColumnSeries series = (ColumnSeries)(myChart.Series[0]);
            MonthlyActivity sales = (MonthlyActivity)(series.SelectedItem);
            ShowDetailsView(sales.DepotActivity);
        }
        private void ShowDetailsView(List<DepotActivity> departmentSales)
        {
            // Create the pie series associated with the details for a month
            PieSeries pieSeries = new PieSeries();
            pieSeries.IndependentValueBinding = new Binding("Depot");
            pieSeries.DependentValueBinding = new Binding("TotalActivity");
            pieSeries.IsSelectionEnabled = true;
            pieSeries.SelectionChanged += new SelectionChangedEventHandler(pieSeries_SelectionChanged);
            pieSeries.ItemsSource = departmentSales;

            // Make sure only the summary series is visible
            myChart.Series.Clear();
            myChart.Series.Add(pieSeries);
        }

        void pieSeries_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ShowSummaryView();
        }
        protected void ContentPopup_MouseEnter(object sender, RoutedEventArgs e)
        {
        }

        protected void ContentPopup_MouseLeave(object sender, RoutedEventArgs e)
        {
        }

        private void Find_Click(object sender, RoutedEventArgs e)
        {
            VirtualEarthService.GeocodeServiceClient geocodeClient = new VirtualEarthService.GeocodeServiceClient("CustomBinding_IGeocodeService");

            VirtualEarthService.GeocodeRequest request = new VirtualEarthService.GeocodeRequest();
            request.Query = txtaddress.Text;

            request.Credentials = new Credentials();
            request.Credentials.ApplicationId = App.Current.Resources["MyCredentials"] as string;

            geocodeClient.GeocodeCompleted += new EventHandler<VirtualEarthService.GeocodeCompletedEventArgs>(client_GeocodeCompleted);
            geocodeClient.GeocodeAsync(request);

        }

        private void client_GeocodeCompleted(object sender, VirtualEarthService.GeocodeCompletedEventArgs e)
        {
            VirtualEarthService.GeocodeResponse response = e.Result;
            if (response.Results.Count > 0)
            {
                VirtualEarthService.GeocodeResult result = response.Results.First();
                if (result.Locations.Count > 0)
                {

                    Pushpin pushpin = new Pushpin();

                    Location location = new Location(result.Locations.First().Latitude, result.Locations.First().Longitude);

                    pushpin.Location = location;

                    MyMap.Children.Add(pushpin);

                    MyMap.SetView(result.BestView);

                }
            }
        }

        private void btnLon_Click(object sender, RoutedEventArgs e)
        {
            MyMap.Mode = new RoadMode();
            MyMap.SetView(new Location(51.50699, -0.127130), 8.0);
        }

        private void btnHam_Click(object sender, RoutedEventArgs e)
        {
            MyMap.Mode = new RoadMode();
            MyMap.SetView(new Location(53.55342,9.9992447), 8.0);
        }

        private void btnMaa_Click(object sender, RoutedEventArgs e)
        {
            MyMap.Mode = new RoadMode();
            MyMap.SetView(new Location(13.07999, 80.270030), 8.0);
        }

        private void btnDxb_Click(object sender, RoutedEventArgs e)
        {
            MyMap.Mode = new RoadMode();
            MyMap.SetView(new Location(25.271149, 55.32908), 8.0);
        }

        private void btnSin_Click(object sender, RoutedEventArgs e)
        {
            MyMap.Mode = new RoadMode();
            MyMap.SetView(new Location(1.3219999, 103.82099), 8.0);
        }

        private void btnHkg_Click(object sender, RoutedEventArgs e)
        {
            MyMap.Mode = new RoadMode();
            MyMap.SetView(new Location(22.33622, 114.1860), 8.0);
        }

        private void btnNYK_Click(object sender, RoutedEventArgs e)
        {
            MyMap.Mode = new RoadMode();
            MyMap.SetView(new Location(40.7199, -74.0030), 9.0);
        }
    }
}
